import { Copy } from '@/art';
import React, { useEffect, useRef, useState } from 'react';
import { createPortal } from 'react-dom';
import Viewer from 'viewerjs';
import 'viewerjs/dist/viewer.min.css';
import { SVG } from '../../gimd/SVG';
import { useArticleDetail } from '../../hooks/useArticleDetail';
import Button from '../Button';
import useToast from '../Toast';
import { CodeViewer } from './CodeViewer';
import styles from './index.module.less';

export interface IArticleViewProps extends React.HTMLAttributes<HTMLDivElement> {
  article_id?: string;
}
export function ArticleView(props: IArticleViewProps): React.ReactElement {
  const { article_id, ..._p } = props;
  const [toast, toast_ctx, useAutoToast] = useToast()
  const ref_article = useRef<HTMLDivElement>(null);
  const [code_viewers, set_code_viewer] = useState<CodeViewer[]>()
  const { data, error } = useArticleDetail({ article_id, also: 'html' })
  useAutoToast(error)
  useEffect(() => {
    const ele = ref_article.current;
    if (!ele || !data || !data.content) {
      set_code_viewer([]);
      return;
    }
    ele.innerHTML = data.content;
    document.title = `Gim's ink: ${data.title}`

    const code_viewer_list: CodeViewer[] = []
    for (const ele_code of ele.querySelectorAll('code')) {
      const ele = ele_code.parentElement
      if (ele?.tagName !== 'PRE') continue;
      const code_viewer = new CodeViewer(ele)
      code_viewer_list.push(code_viewer)
    }
    set_code_viewer(code_viewer_list);
    const gallery = new Viewer(ele)
    return () => {
      document.title = `Gim's ink`;
      code_viewer_list.forEach(v => v.release())
      gallery.destroy();
    }
  }, [data])

  return (
    <div {..._p}>
      {toast_ctx}
      <div ref={ref_article} className={styles.article} />
      {code_viewers?.map((code_viewer, idx) => {
        const container = code_viewer.ele_head;
        const key = '' + idx;
        return createPortal((
          <Button
            kind='icon'
            size='s'
            title='复制代码'
            onClick={() => code_viewer.copy_to_clipboard().then(() => toast({ id: 'A', msg: "已复制至剪切板", badge_color: 'rgb(124,172,248)' }))}>
            <SVG c={Copy} width={12} height={12} />
          </Button>
        ), container, key)
      })}
    </div>
  );
}
